<?php
namespace App\Http\Controllers\Api;
use App\Models\FeeGood;
use App\Models\FeeItem;
use App\Models\Set;
use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;

class Fee extends ApiController{
    public function index(Request $req){
        $type = $req->post('type',0);
        $dftype = $req->post('dftype','');
        $list = FeeGood::where('type',$type)->where('status',0)->orderByRaw('title+0')->get();
        $goods = [];
        $min = 100;
        foreach ($list as $value) {
            $g = array('gid'=>$value->id,'price'=>$value->title);
            $price = FeeItem::where('gid',$value->id)->where('status',0);
            if ($type == 1) $price->whereRaw("(extra='' or extra='{$dftype}')");
            $price = $price->min('costprice');
            if ($price <= 0) continue;
            $g['pay'] = round($price + $value->marketprice,2);
            $g['reduce'] = round($g['price'] - $g['pay'],2);
            $g['discount'] = round($g['pay'] / floatval($g['price']) * 10,1) * 10;
            $min = min($min,$g['discount']);
            $goods[] = $g;
        }
        $set = Set::getSet('base');
        $rule = $set['feerule'];
        if ($type > 0) $rule = $set['feerule'.($type+1)]??'';
        $title = '话费';
        $img = 'hf_icon.jpeg';
        if ($type == 1){
            $title = '电费';
            $img = 'df_icon.png';
        }elseif ($type == 2){
            $title = '燃气费';
            $img = 'rq_icon.png';
        }
        $sharedata = array(
                'title'=> $title.'充值',
                'imgUrl'=>"https://".$req->host()."/static/".$img,
                'desc'=>"限时{$min}折起",
                'link'=>"https://".$req->host()."/".$req->shopagent->code."/#/pages/index/fee?type=".$type
        );
        wxresp(1,['goods'=>$goods,'rule'=>$rule,'sharedata'=>$sharedata]);
    }
}